import axios from 'axios';
import { ElMessage } from 'element-plus';

const http = axios.create({
    baseURL:"/api",
    timeout:30000,
    headers: {
        get: {
            'Content-Type':'application/x-www-form-urlencoded; charset=utf-8'
        },
        post: {
            'Content-Type':'application/json; charset=utf-8'
        }
    }
})

http.interceptors.request.use(
    (config)=>{
        // config.headers['Authorization'] = Vue.coo
        //添加token
        const token = localStorage.getItem('token');
        if(token) {
            config.headers["Authorization"] = token;
        }
        return config;
    },
    (error)=>Promise.reject(error)
)

http.interceptors.response.use(
    (response)=>{
        if(response.status == 200) {
            if(response.data.code == 200) {
                return response.data;
            }
            //弹窗报错
            ElMessage({
                message:response.data.msg,
                type:'error',
                duration:1500,
                customClass:"element-error-message-zindex"
            })
            handerErrorCode(response.data.code);
            return Promise.reject(new Error(response.data.msg))
        }
    },
    (error)=>{
        handerErrorResponse(error.response.status)
        return Promise.reject(error)
    }
)

function handerErrorCode(status:number) {
    switch (status){
        case 401:
            localStorage.removeItem("token");
            window.location.href = '/manage/login'
        case 405:
            break;
    }
}

function handerErrorResponse(status:number) {
    let msg = "请求错误，状态码："+status;
    switch (status){
        case 400:
            msg = "未授权，请重新登录";
        case 405:
            msg = "请求方式错误";
        case 500:
            msg = "服务器异常，请稍后重试";   
    }
    ElMessage({
        message:msg,
        type:'error',
        duration:1500,
        customClass:"element-error-message-zindex"
    })
}

const httpRequest = {
    async get<T>(url:string,params:any):Promise<T> {
        return await http.get(url,params);
    },

    async post<T>(url:string,params:any):Promise<T> {
        return await http.post(url,params);
    },

    async postNoParam<T>(url:string):Promise<T> {
        return await http.post(url);
    },


    async postLink<T>(url:string,params:any):Promise<T> {
        const keys = Object.keys(params);
        if(keys.length > 0) {
            url += "?";
            for(let i=0;i<keys.length ;i++) {
                let tempKey = keys[i];
                url += `${tempKey}=${params[tempKey]}`;
                if(i!= keys.length-1) {
                    url += '&';
                }
            }
        }
        return await http.post(url);
    },

    async put<T>(url:string,params:any):Promise<T> {
        return await http.put(url,params);
    },

    async delete<T>(url:string,params:any):Promise<T> {
        return await http.delete(url,params);
    }
}
export default httpRequest;